//
//  SecondView.swift
//  Speek
//
//  Created by MikeHo on 2023/4/15.
//

import SwiftUI
import CoreData

private let TITLES = ["明细","预算","分析"]

struct SecondView: View {
    
    //@State private var monthlyBillShowing : [MonthlyBill] = []
    @Environment(\.presentationMode) var presentationMode
    @State private var selectedIndex = 0
    
    //View Properties
    @State private var addDetail:Bool = false           //添加账单
    @State private var isShowTypeSelect:Bool = false    //选择显示账单种类
    @State private var isEditBudget:Bool = false        //编辑预算
    @State private var isEditBudgetSuccess = false      //编辑预算是否成功
    @State private var showAdvice:Bool = false          //获取分析建议

    //选择日期
    @State private var isShowDateSelect:Bool = false    //是否显示日期选择
    @State private var selectYear:String = ""           //选择的年份
    @State private var selectMonth:String = ""          //选择的月份

    //分析
    @State private var analysisData: AnalysisData = AnalysisData(totalIncome: 0, totalExpense: 0, maxAmountBill: BillDetail() , maxChangedBill: MaxChangedBill(year: "", month: "", type: "", changedAmount: 0, changedRatio: 0)) //待分析的数据
    @State private var outputText = ""                  //输出的建议
    @State private var isAdviceLoading = false   //分析时加载

    var body: some View {
        VStack{
            
            //下滑返回
            HStack{
                Spacer()
                Image("Jump")
                    .aspectRatio(contentMode: .fit)
                    .contentShape(Rectangle())
                    .rotationEffect(Angle(degrees: 180))
                    .onTapGesture {
                        presentationMode.wrappedValue.dismiss()
                    }
                Spacer()
            }
            .background(Color.black)
            .frame(height: 20)
            .padding(.top,20)
            .gesture(
                DragGesture(minimumDistance: 100)
                    .onEnded{value in
                        if(value.translation.height>0){
                            presentationMode.wrappedValue.dismiss()
                        }
                    }
            )
            
            Spacer()
            
            //页面
            VStack(alignment: .leading){
                //选项卡
                classifyTopView
                //页面
                pageView
            }

            //添加账单页面
            .sheet(isPresented: $addDetail){
                DetailAdd()
                    .presentationDetents([.large])
                    .presentationDragIndicator(.hidden)
                    .interactiveDismissDisabled()
                    .navigationBarTitle("",displayMode: .inline)
            }
            
            //编辑预算页面
            .sheet(isPresented: $isEditBudget) {
                BudgetEdit(year: selectYear,month: selectMonth,isEditSuccess:$isEditBudgetSuccess)
                    .presentationDetents([.height(200)])
                    .presentationDragIndicator(.hidden)
                    .interactiveDismissDisabled()
                    .navigationBarTitle("",displayMode: .inline)
                                               
            }
            
            //选择预算日期页面
            .sheet(isPresented: $isShowDateSelect) {
                BudgetDatePicker(selectYear: $selectYear,selectMonth:$selectMonth)
                    .presentationDetents([.height(200)])
                    .presentationDragIndicator(.hidden)
                    .interactiveDismissDisabled()
                    .navigationBarTitle("",displayMode: .inline)
            }
            
            //获取建议页面
            .sheet(isPresented: $showAdvice) {
                AnalysisAdvise(analysisData: $analysisData, outputText: $outputText,isLoading: $isAdviceLoading)
                    .presentationDetents([.large])
                    .presentationDragIndicator(.hidden)
                    .interactiveDismissDisabled()
                    .navigationBarTitle("",displayMode: .inline)
            }
            
            
            
        }
        .onAppear {
            if selectYear.isEmpty || selectMonth.isEmpty {
                let (currentYear, currentMonth) = getCurrentYearAndMonth()
                selectYear = currentYear
                selectMonth = currentMonth
            }
        }
        //点击画面其他部分隐藏设置界面
        .onTapGesture {
            addDetail = false
            isShowTypeSelect = false
            isEditBudget = false
            showAdvice = false
        }
    }
}

extension SecondView{
    
    private var pageView : some View{
        TabView(selection: $selectedIndex){
            ForEach(0..<TITLES.count){index in
                switch index {
                case 0:
                    //明细界面
                    DetailView(isShowTypeSelect: $isShowTypeSelect).tag(index)
                case 1:
                    //预算界面
                    BudgetView(isEditBudget: $isEditBudget, isShowBudgetDateSelect: $isShowDateSelect, isEditBudgetSuccess: $isEditBudgetSuccess,selectBudgetYear: $selectYear, selectBudgetMonth: $selectMonth).tag(index)
                case 2:
                    //分析界面
                    AnalysisView(year: $selectYear, month: $selectMonth,analysisData: $analysisData) .tag(index)
                default:
                    EmptyView()
                }
            }
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
}


extension SecondView{
 
    private var classifyTopView:some View{
        
        VStack{
            HStack{

                //根据页面显示不同按键
                if(selectedIndex == 0){
                    
                    //选择账单分类按钮
                    Button{
                        isShowTypeSelect = true
                    }label: {
                        Image(systemName: "line.horizontal.3.decrease.circle")
                        Text("选择分类")
                    }
                    
                    Spacer()
                    
                    //添加账单按钮
                    Button{
                        addDetail = true
                    }label: {
                        Text("添加")
                        Image(systemName: "plus")
                    }
                }else if (selectedIndex == 1){
                    
                    //选择日期按钮
                    Button{
                        isShowDateSelect = true
                    }label: {
                        Image(systemName: "calendar")
                        Text("日期")
                    }
                    
                    Spacer()
                    
                    //预算编辑按钮
                    Button{
                        isEditBudget = true
                    }label: {
                        Text("编辑")
                        Image(systemName: "square.and.pencil")
                    }
                }else{
                    //选择日期按钮
                    Button{
                        isShowDateSelect = true
                    }label: {
                        Image(systemName: "calendar")
                        Text("日期")
                    }
                    
                    Spacer()
                    
                    //分析消费行为按钮
                    Button{
                        showAdvice = true
                        isAdviceLoading = true
                    }label: {
                        Text("生成建议")
                        Image(systemName: "waveform.path.ecg")
                    }
                }
            }
            .font(.headline)
            .foregroundColor(.white)
            .padding(.horizontal, 10)
            
            //切换三个页面
            HStack{
                ScrollView(.horizontal,showsIndicators: false){
                    VStack(alignment: .leading, spacing:0){
                        HStack(spacing: 0){
                            ForEach(0..<TITLES.count,id:\.self){index in
                                Text(TITLES[index])
                                    .fontWeight(self.selectedIndex == index ? .bold:nil)
                                    .font(.system(size:18))
                                    .foregroundColor(self.selectedIndex == index ? Color(red:0.9922,green:0.1569,blue:0.3137 ):nil)
                                    .frame(width: 130,height: 32)
                                    .onTapGesture {
                                        self.selectedIndex = index
                                    }
                            }
                        }
                        HStack{
                            Capsule().fill(Color(red:0.9922,green:0.1569,blue:0.3137 ))
                                .frame(width: 130,height: 2)
                        }
                        .frame(width: 130)
                        .offset(x: CGFloat(selectedIndex * 130))
                        .animation(.default)
                    }
                    .padding(.leading,10)
                }
            }
            .background(Color.red.opacity(0.0))
            Divider()
        }
    }
}

struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        MainMenu()
    }
}

func getCurrentYearAndMonth() -> (String, String) {
    let currentDate = Date()
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy"
    let year = dateFormatter.string(from: currentDate)
    
    dateFormatter.dateFormat = "M"
    let month = dateFormatter.string(from: currentDate)
    
    return (year, month)
}
